﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using monadsphere.js;
using monadsphere.dom;
using monadsphere.dom.html2;
using monadsphere.dom.events;

/// <summary>
/// Summary description for demo
/// </summary>
/// <summary>
/// This component wraps two input fields, a button, and a result display.
/// 
/// It also has a value property.
/// 
/// It defines a "compute" event, that is triggered when the button is clicked.
/// 
/// </summary>
/// 

namespace monadsphere.demo.compute {

    public class ComputeComponent: HTMLDivElement {

        /// <summary>
        /// Can not directly instantiate.
        /// </summary>
        protected ComputeComponent() {
        }

        /// <summary>
        /// The way the framework creates this component.
        /// </summary>
        /// <param name="handle"></param>
        public ComputeComponent(JSVar handle)
            : base(handle) {

            // if it is not to create the component
            if (!handle.initialize) {
                return;
            }

            HTMLDocument doc = HTMLDocument.instance;

            // input1
            HTMLInputElement input1 = doc.createElement<HTMLInputElement>();
            appendChild(input1);

            // multiplier x
            HTMLSpanElement multiplier = doc.createElement<HTMLSpanElement>();
            multiplier.textContent = " × ";
            appendChild(multiplier);

            // input2
            HTMLInputElement input2 = doc.createElement<HTMLInputElement>();
            appendChild(input2);

            // the button
            ButtonInputElement button = doc.createElement<ButtonInputElement>();
            button.value = "Compute";
            appendChild(button);

            // result area
            HTMLDivElement result = doc.createElement<HTMLDivElement>();
            result.style.padding = "5px";
            appendChild(result);

            // sets properties that are retrievable
            setProperty("input1", input1);
            setProperty("result", result);
            setProperty("input2", input2);

            button.onclick += new HtmlEventHandler<MouseEventListener<HTMLElement>>(compute);
        }

        protected void compute(MouseEvent<HTMLElement> e) {
            Node a = e.target.parentNode;
            a.fireCustomEvent<ComputeComponent>("compute", true, true, null);
        }

        public JSString value {
            get {
                return getProperty<HTMLDivElement>("result").textContent;
            }
        }

        public HtmlEventHandler<EventListener<ComputeComponent>> oncompute {
            get {
                return new HtmlEventHandler<EventListener<ComputeComponent>>();
            }

            set {
                this.addCustomEventListener("compute", value.handler, value.useCapture);
            }
        }
    }
}
